
class StoreController < ApplicationController
  before_filter :authorize
  #START:before_filter
  # before_filter :find_cart, :except => :empty_cart
  #END:before_filter
  
  def index
    redirect_to :controller=>'orders',:action => :index
  end
  
  # GET /orders/1/lines
  def order_lines
    if prepare_order and params[:print]
      render :layout => 'order'  
    end
  end
  
  def order_lines_edit
    prepare_order
  end
  
  def query_order
    @order = Order.new
  end
  
  def do_query_order    
    conditions = ["1=1 "]
    if not params[:order]
      render :text => '<div id="error">查询信息不完整</div>', :layout => true
      return 
    end
    if params[:order][:order_num] and not params[:order][:order_num].empty?
      conditions[0] << " and order_num like ? " 
      conditions << "%"+params[:order][:order_num]+"%"
    end
    
    if not params[:order][:customer].empty?
      conditions[0] << " and customer = ? "
      conditions << params[:order][:customer]
    end
    
    if not params[:order][:status].empty?
      conditions[0] << " and status = ? "
      conditions << params[:order][:status]
    end
    
    if not admin?
      conditions[0] << " and user = ? " 
      conditions << cur_user.name
    end
    
    order_by = 'created_at desc'
    if params[:order_by] and not params[:order_by].empty?
      order_by = params[:order_by].join(',')
    end
    
    @orders = Order.find :all, :conditions => conditions, :order => order_by #, :page => params[:page]
    params[:query]==true
    render :template => 'orders/index'
  end
  
  def order_newline
     @order = Order.find_by_order_num(params[:id])
     return if cannt_do_by @order.user
     @line = Line.new
  end
  
  def order_editline
    @line = Line.find params[:id]
    @order = Order.find_by_order_num @line.order_num
    return if cannt_do_by @order.user
  end

#  def update_order_lines
#    @order = Order.find_by_order_num(params[:id])
#    return if cannt_do_by @order.user
#    @order.update_attributes(params[:order])
#    begin      
#      Line.transaction do      
#        params[:line].each do |id, aline|
#          if id
#            updateline = Line.find(id)       
#            updateline.update_attributes!(aline)       
#          else
#            newaline = Line.create(aline)
#          end
#        end      
#      end      
#      flash[:notice] = "保存数据成功"      
#    rescue      
#      flash[:notice] = "保存数据失败"      
#    end       
#  end
     
  private
  def prepare_order
    @order = Order.find_by_order_num params[:id]    
    if @order.nil?
      flash[:notice] = '记录未找到'
      false
    else
      return false if cannt_do_by @order.user
      @customer = Customer.find_by_customer @order.customer
      @lines = Line.find :all, :conditions => ['order_num = ?', @order.order_num]
    end
  end
end
